package sdkshell.kuaiyan.com.kuaiyansdk.http;

import com.wmcsk.dl.util.LogUtils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.concurrent.Executors;

import sdkshell.kuaiyan.com.kuaiyansdk.SdkInit;
import sdkshell.kuaiyan.com.kuaiyansdk.http.Ihttp.NetBuilderConfig;
import sdkshell.kuaiyan.com.kuaiyansdk.http.callback.ResultCallback;
import sdkshell.kuaiyan.com.kuaiyansdk.listener.HttpPostInterface;
import sdkshell.kuaiyan.com.kuaiyansdk.util.StringUtils;

/**
 * Created by admin on 2016/8/29.
 */
public class HttpPostSend implements HttpPostInterface {
    public HttpPostSend() {
        super();
    }
    @Override
    public void postData(NetBuilderConfig config, Map<String, String> params, ResultCallback callback, String url) {
        Executors.newSingleThreadExecutor().execute(new PostTask(new WeakReference<HttpPostSend>(this),callback,config));
    }
    static class PostTask implements Runnable {
        private WeakReference<HttpPostSend> postSendWeakReference;
        private ResultCallback callback;
        private NetBuilderConfig config;
        public PostTask(WeakReference<HttpPostSend> postSendWeakReference, ResultCallback callback, NetBuilderConfig config){
            this.postSendWeakReference = postSendWeakReference;
            this.callback = callback;
            this.config = config;
        }
        @Override
        public void run() {
            if(postSendWeakReference!=null){
                HttpPostSend httpPostSend = postSendWeakReference.get();
                if(httpPostSend!=null) {
                    httpPostSend.SendMessage(config,callback);
                }
            }
        }
    }

    private  void SendMessage(NetBuilderConfig config,final ResultCallback callback){
        String url = config.getNetConfig().getUrl();
        String content = config.getNetConfig().getContent();
        if(content == null){
            content = StringUtils.getUrlFromUrlAndParams("",config.getNetConfig().getParams()).toString().replaceFirst("\\?","");
        }
        try {
            sendMessage(url, content,callback,config);
        }catch (final Exception e){
            SdkInit.getUiHandle().post(new Runnable() {
                @Override
                public void run() {
                    if(callback!=null){
                        callback.onError(e,e.getMessage());
                    }
                }
            });
        }
    }

    public void sendMessage(String url, String content, final ResultCallback callback, NetBuilderConfig config) throws Exception {
        String urlPath=url;
        URL urls = new URL(urlPath);
        // 连接
        HttpURLConnection conn = (HttpURLConnection) urls
                .openConnection();
        conn.setRequestMethod("POST");
        conn.setReadTimeout(5000);
        conn.setDoOutput(true);
        OutputStream out = conn.getOutputStream();
        if(content!=null) {
            out.write(content.getBytes());
        }
        // 响应结果
        final StringBuilder results=new StringBuilder();
        final int responseCode = conn.getResponseCode();
        if (200 == responseCode) {
            InputStream input = conn.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(input,config.getNetConfig().getEncoding()));
            String line = null;
            int temp = 0;
            while ((line = bufferedReader.readLine()) != null) {
                results.append(line);
            }
            SdkInit.getUiHandle().post(new Runnable() {
                @Override
                public void run() {
                    if(callback!=null){
                        callback.onResponse(results.toString(),results.toString());
                    }
                }
            });
        }else{
            SdkInit.getUiHandle().post(new Runnable() {
                @Override
                public void run() {
                    if(callback!=null){
                        RuntimeException e = new RuntimeException("网络请求失败"+responseCode);
                        callback.onError(e,e.getMessage());
                    }
                }
            });
            LogUtils.getNewInstance("HttpPostSend").eob("网络请求失败"+responseCode);
        }

    }
}
